//
//  LGPlayVideoTool.m
//  XieHeHeartDisease
//
//  Created by 1234 on 2024/1/23.
//

#import "LGPlayVideoTool.h"

#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import "ZFPlayerController.h"
#import "ZFAVPlayerManager.h"
#import "ZFPlayerControlView.h"
@interface LGPlayVideoTool()
/**   */
@property (nonatomic , strong)ZFPlayerController *player;
/**   */
@property (nonatomic , strong)ZFPlayerControlView *controlView;
/**   */
@property (nonatomic , strong)UIView *fatherView;
/**   */
@property (nonatomic , strong)UIButton *closeBtn;

@end

@implementation LGPlayVideoTool

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubView];
        [self videoPlayerCallBack];
    }
    return self;
}

-(void)setUrl:(NSString *)url{
    _url = url;
    self.player.assetURL = [NSURL URLWithString:url];
    AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString:url]];
    NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
    AVAssetTrack *videoTrack = tracks[0];
    CGSize videoSize = CGSizeApplyAffineTransform(videoTrack.naturalSize, videoTrack.preferredTransform);
    videoSize = CGSizeMake(fabs(videoSize.width), fabs(videoSize.height));
    CGFloat videoHeight = Screen_W/16.0*9.0;
    videoHeight = Screen_W*videoSize.height/videoSize.width;
    /// 播放器相关
    self.fatherView.frame = CGRectMake(0, (Screen_H-videoHeight)/2.0, Screen_W, videoHeight);
    [self.controlView showTitle:@"" coverImage:nil fullScreenMode:ZFFullScreenModeAutomatic];
    [self.player.currentPlayerManager play];
}

-(void)setPath:(NSString *)path{
    _path = path;
    self.player.assetURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",path]];
    AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString:LGNSString(path)]];
    NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
    AVAssetTrack *videoTrack = tracks[0];
    CGSize videoSize = CGSizeApplyAffineTransform(videoTrack.naturalSize, videoTrack.preferredTransform);
    videoSize = CGSizeMake(fabs(videoSize.width), fabs(videoSize.height));
    CGFloat videoHeight = Screen_W/16.0*9.0;
    videoHeight = Screen_W*videoSize.height/videoSize.width;
   
    /// 播放器相关
    self.fatherView.frame = CGRectMake(0, (Screen_H-videoHeight)/2.0, Screen_W, videoHeight);
    [self.controlView showTitle:@"" coverImage:nil fullScreenMode:ZFFullScreenModeAutomatic];
}

//视频播放回调
- (void)videoPlayerCallBack{
    __weak typeof(self) weakSelf = self;
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        myDelegate.allowOrentitaionRotation = isFullScreen;
    };
    
    // 播放完成
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        //回到半屏
        [weakSelf.player enterFullScreen:NO animated:YES];
        [weakSelf.player.currentPlayerManager seekToTime:0 completionHandler:^(BOOL finished) {
            [weakSelf.player.currentPlayerManager pause];
        }];
//        if (weakSelf.index<weakSelf.videoArray.count-1) {
//            weakSelf.index++;
//        }else{
//            //播放结束
//            [weakSelf.player stop];
//        }
    };
    //播放中
    self.player.playerPlayTimeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval currentTime, NSTimeInterval duration) {
      
        CGFloat percent = currentTime/duration;
//        if (percent>0.9) {
//            [weakSelf playEndRecord];
//        }
    };
}

-(void)closeViewAnimation{
    [self.player.currentPlayerManager stop];
    [UIView animateWithDuration:0.4 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.backgroundColor = [UIColor blackColor];
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    playerManager.shouldAutoPlay = YES;
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.fatherView];
    self.player.controlView = self.controlView;
    self.player.pauseWhenAppResignActive = YES;//设置退到后台继续播放
    self.player.pauseByEvent = YES;
    [self addSubview:self.fatherView];
    [self addSubview:self.closeBtn];
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeViewAnimation)]];
}

//视频的占位View
-(UIView *)fatherView{
    if (!_fatherView) {
        CGFloat height = Screen_W/16.0*9.0;
        _fatherView = [[UIView alloc] initWithFrame:CGRectMake(0, (Screen_H-height)/2.0, Screen_W, height)];
        _fatherView.backgroundColor = [UIColor blackColor];
    }
    return  _fatherView;
}

- (ZFPlayerControlView *)controlView{
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
        _controlView.autoHiddenTimeInterval = 5;
        _controlView.autoFadeTimeInterval = 0.5;
        _controlView.prepareShowLoading = YES;
        _controlView.prepareShowControlView = NO;
    }
    return _controlView;
}

-(UIButton *)closeBtn{
    if(!_closeBtn){
        _closeBtn = [UIButton buttonWithImage:@"" frame:CGRectMake((Screen_W-viewPix(50))/2.0, Screen_H-viewPix(70), viewPix(40), viewPix(40))];
        [_closeBtn setBackgroundImage:[UIImage imageNamed:@"弹框关闭"] forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(closeViewAnimation) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}

@end
